/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package form;
/**
 *
 * @author THANHTAM
 */
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class BlackList extends javax.swing.JFrame {

    /**
     * Creates new form BlackList
     */
    public BlackList() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnAdd = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();
        txtWebLink = new javax.swing.JTextField();
        brnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        lsbxBlackList = new java.awt.List();
        cbxLoai = new java.awt.Choice();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnAdd.setText("Add");
        btnAdd.setName("btnAdd");
        btnAdd.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnAddMouseClicked(evt);
            }
        });
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnRemove.setText("Remove");
        btnRemove.setName("btnRemove");
        btnRemove.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnRemoveMouseClicked(evt);
            }
        });

        txtWebLink.setName("txtWebLink");

        brnOK.setText("OK");
        brnOK.setName("btnOK");
        brnOK.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                brnOKMouseClicked(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.setToolTipText("");
        btnCancel.setName("btnCancel");

        cbxLoai.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbxLoaiItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lsbxBlackList, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnRemove, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(38, 38, 38)
                        .addComponent(cbxLoai, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(brnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(btnCancel))
                        .addComponent(txtWebLink, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(32, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lsbxBlackList, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(txtWebLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnAdd)
                            .addComponent(cbxLoai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(btnRemove)
                        .addGap(117, 117, 117)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnCancel)
                            .addComponent(brnOK))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRemoveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRemoveMouseClicked
        // TODO add your handling code here:
        int a = lsbxBlackList.getSelectedIndex();
        if(a == -1)
        {
            JOptionPane.showMessageDialog(this,"Ban chua chon link web");
        }
        else
        {
            String b = lsbxBlackList.getSelectedItem();
            lsbxBlackList.remove(a);
        }
    }//GEN-LAST:event_btnRemoveMouseClicked

    private void btnAddMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAddMouseClicked
        // TODO add your handling code here:
        String Add = txtWebLink.getText().toString();
        if(Add.length() == 0)
        {
            JOptionPane.showMessageDialog(this,"Ban chua nhap link web");
        }
        else
        {
            boolean Check = true; //kiem tra link web da co hay chua
            for(int i = 0; i < lsbxBlackList.getItemCount(); i++)
            {
                if(Add.compareTo(lsbxBlackList.getItem(i).toString())==0)
                {
                    JOptionPane.showMessageDialog(this,"Da ton tai");
                    Check = false;
                    break;
                }
            }
            //ko trung moi them
            if(Check)
            {            
                int temp = lsbxBlackList.getRows();
                lsbxBlackList.add(Add, temp);
                txtWebLink.setText("");
            }
        }
    }//GEN-LAST:event_btnAddMouseClicked

    private void brnOKMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_brnOKMouseClicked
        // TODO add your handling code here:
        createDOMTree();
    }//GEN-LAST:event_brnOKMouseClicked

    private void cbxLoaiItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbxLoaiItemStateChanged
        // TODO add your handling code here:
        
    }//GEN-LAST:event_cbxLoaiItemStateChanged

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnAddActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException{
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BlackList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BlackList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BlackList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BlackList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new BlackList().setVisible(true);
            }
        });
        
        try {
          // Get DocumentBuilder
          DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
          // Parse and load into memory the Document
          Document doc = (Document) builder.parse( new File("BlackList.xml"));

          AddDOMTree((Node) doc);
          
        } catch (SAXParseException spe) {
            System.out.println(spe);
            }
    }
    
    public static void AddDOMTree(Node node) {
        int type = node.getNodeType();
        switch (type) {
            // print the document element
            case Node.DOCUMENT_NODE: {
              //System.out.println("<?xml version=\"1.0\" ?>");
              AddDOMTree((Node) ((Document)node).getDocumentElement());
              break;
            }

            // print element with attributes
            case Node.ELEMENT_NODE: {
              System.out.print("<");
              System.out.print(node.getNodeName());     //BlackList
              NamedNodeMap attrs = node.getAttributes();
              for (int i = 0; i < attrs.getLength(); i++) {
                Node attr = (Node) attrs.item(i);
                System.out.print(" " + attr.getNodeName().trim() +
                                 "=\"" + attr.getNodeValue().trim() +
                                 "\"");
            }
            System.out.println(">");

            NodeList children = node.getChildNodes();
            if (children != null) {
              int len = children.getLength();
              for (int i = 0; i < len; i++)
                AddDOMTree((Node) children.item(i));
            }

            break;
            }

            // print text
            case Node.TEXT_NODE: {
              System.out.print(node.getNodeValue().trim());
              break;
            }
        }

        if (type == Node.ELEMENT_NODE) {
          System.out.println();
          System.out.print("</");
          System.out.print(node.getNodeName().trim());
          System.out.print('>');
        }
    }
    
    public static void createDOMTree() /*throws TransformerConfigurationException, TransformerException*/{
     try{

	  //DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	  DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

	  //root elements
	  Document doc = builder.newDocument();

          Element rootElement = doc.createElement("BlackList");
          rootElement.setAttribute("Ten", "CDKTCT");

          Element lop1 = doc.createElement("Web");
          lop1.setAttribute("Ten", "CDTH08A");
          lop1.setAttribute("MaSo", "2");

          Element hocsinh1 = doc.createElement("Hocsinh");
          hocsinh1.appendChild(doc.createTextNode("A"));

          Element hocsinh2 = doc.createElement("Hocsinh");
          hocsinh2.appendChild(doc.createTextNode("B"));

          lop1.appendChild(hocsinh1);
          lop1.appendChild(hocsinh2);

          rootElement.appendChild(lop1);

          doc.appendChild(rootElement);

          //write the content into xml file
	  TransformerFactory transformerFactory = TransformerFactory.newInstance();
	  Transformer transformer = transformerFactory.newTransformer();
	  DOMSource source = new DOMSource(doc);
	  StreamResult result =  new StreamResult(new File("BlackListOut.xml"));
	  transformer.transform(source, result);

	  System.out.println("Done");

     }catch(ParserConfigurationException pce){
         System.out.println(pce);
     }catch(TransformerException tfe){
          System.out.println(tfe);
     }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton brnOK;
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnRemove;
    private java.awt.Choice cbxLoai;
    private java.awt.List lsbxBlackList;
    private javax.swing.JTextField txtWebLink;
    // End of variables declaration//GEN-END:variables

}
